package com.vhly.ddxdecompiler.dexreader.file.mixeditem;

import com.vhly.ddxdecompiler.dexreader.file.DexFile;
import com.vhly.ddxdecompiler.dexreader.io.DexInputStream;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;

/**
 * Created by IntelliJ IDEA.
 * User: vhly
 * Date: 2009-10-15
 * Time: 12:46:45
 *
 * @author vhly[FR]
 */
public final class ProtoIdItem extends IndexedItem {
    int shortyIdx;
    int returnIdx;
    int paramsOff;

    private StringIdItem shortyItem;
    private TypeIdItem returnItem;

    private TypeListItem types;

    private DexFile dex;

    public ProtoIdItem(DexFile dexFile) {
        dex = dexFile;
    }

    public void read(DexInputStream din) throws IOException {
        shortyIdx = din.readInt();
        returnIdx = din.readInt();
        paramsOff = din.readInt();
    }

    public void write(DataOutputStream dout) throws IOException {
    }

    public void reloc(ByteArrayInputStream bin, int offset) throws IOException {
        shortyItem = dex.getStringIds().indexOf(shortyIdx);
        returnItem = dex.getTypeIds().indexOf(returnIdx);
        // TODO process paramsOff 's content
        int off = paramsOff;
        if (off != 0) {
            types = new TypeListItem(dex);
            String key = Integer.toString(off);
            if (dex.offsetCache.containsKey(key)) {
                types = (TypeListItem) dex.offsetCache.get(key);
            } else {
                bin.reset();
                bin.skip(off - offset);
                DataInputStream din = new DataInputStream(bin);
                DexInputStream dxin = new DexInputStream(din, 1);
                dxin.setOffset(off);
                types.read(dxin);
                dex.offsetCache.put(key, types);
                dxin.close();
                din.close();
            }
        }
    }

    /**
     * 返回Java形式的描述
     *
     * @return String
     */
    public String getJavaDescript() {
        StringBuffer sb = new StringBuffer("(");
        if (types != null) {
            Vector<TypeIdItem> params = types.items;
            int size = params.size();
            if (size > 0) {
                TypeIdItem item;
                for (int i = 0; i < size - 1; i++) {
                    item = params.elementAt(i);
                    sb.append(item.item.toString()).append(',');
                }
                item = params.elementAt(size - 1);
                sb.append(item.item.toString());
            }
            sb.append(')');
        } else {
            sb.append(')');
        }
        sb.append(returnItem.item.toString());
        return sb.toString();
    }
}
